<?php 
	class Users extends CI_Model{

		function __construct(){
			parent::__construct();
		}

		function get_user_list($limit = 0, $offset = 10, $conditions = array()){
			$where = 'WHERE 1=1';
			$today_time = strtotime(date("Y-m-d", time()));
			$today_end_time = $today_time + 3600 * 24;
			if(!empty($conditions['start_time'])){
				$where .= " AND u.add_time >= '{$conditions['start_time']}' ";
			}
			if(!empty($conditions['end_time'])){
				$where .= " AND u.add_time <= '{$conditions['end_time']}' ";
			}
			if(!empty($conditions['nick'])){
				$where .= " AND u.nick LIKE '%{$conditions['nick']}%' ";
			}
			if(isset($conditions['default_child']) && $conditions['default_child'] >= 0 && $conditions['default_child'] != 'all'){
				if($conditions['default_child'] == 0){
					$where .= " AND u.child_id  = 0 ";
				}else{
					$where .= " AND u.child_id > 0 ";
				}
			}
			if(!empty($conditions['user_type'])){
				if($conditions['user_type'] == 1 && empty($conditions['start_time']) && empty($conditions['end_time'])){
					$where .= " AND u.add_time >= '{$today_time}' ";
				}elseif($conditions['user_type'] == 2){
					if(!empty($conditions['start_time'])) $today_time = $conditions['start_time'];
					if(!empty($conditions['end_time'])) $today_end_time = $conditions['end_time'];
					$where .= " AND uvs.last_time >= '{$today_time}' ";
					$where .= " AND uvs.last_time < '{$today_end_time}' ";
				}
			}
			$sql = "SELECT SQL_CALC_FOUND_ROWS u.*, COUNT(t.id) AS count, (select count(id) FROM tiku_user_childrens where user_id=u.id) AS child_count FROM {$this->db->dbprefix}users AS u ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}tasks AS t ON (t.user_id=u.id) ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}user_visit_statistics AS uvs ON(uvs.user_id=u.id) ";
			$sql .= "$where GROUP BY u.id ORDER BY id DESC LIMIT $limit, $offset";
			$result = $this->db->query($sql)->result_array();
			$row_num =  $this->db->query('SELECT FOUND_ROWS() as row_num;')->row_array();
			return array("count" => $row_num['row_num'], "result" => $result);
		}
	}